<style lang="less">
@import "../../styles/common.less";
.ivu-table .table-info-normal td {
  background-color: #2db7f5;
}

.ivu-table .table-info-live td {
  background-color: #e2fcde;
}

.ivu-table .table-info-not-live td {
  background-color: #fee6d4;
}
.ivu-table .table-info-error td {
  background-color: #ffe3e3;
}

.ivu-table .table-info-shrink td {
  background-color: lightgray;
  // margin-left: 10;
}
</style>

<template>
  <div class="margin-top-10">
    <Row type="flex" justify="space-between">
      <Row>
        <Input
          v-model="queryName"
          @on-enter="searchRecord"
          placeholder="请输入姓名..."
          style="width:150px;margin-right:8px"
        ></Input>
        <Select v-model="queryUserType" style="width:150px;margin-right:8px" placeholder="请选择用户类型">
          <Option value key>不限</Option>
          <Option v-for="item in typeList" :value="item.value" :key="item.value">{{ item.label }}</Option>
        </Select>
        <DatePicker
          type="datetimerange"
          v-model="queryDateRange"
          placeholder="选择时间段"
          format="yyyy-MM-dd HH:mm"
          style="width: 300px;margin-right:8px"
        ></DatePicker>
        <Button @click="searchRecord" type="primary">查询</Button>
      </Row>
      <Row style="display: none">
        <Button>导出</Button>
      </Row>
    </Row>
    <div class="margin-top-10">
      <Table
        :row-class-name="rowClassName"
        :columns="recColumn"
        :data="recDataList"
        :loading="tableLoading"
        ref="recTable"
      ></Table>
    </div>
    <Row type="flex" justify="end" class="margin-top-10">
      <Page
        :total="recHistory.total"
        :current="currentPage"
        :page-size="pageSize"
        @on-change="pageQuery"
      >总数为{{recHistory.total}}条</Page>
    </Row>
    <Modal v-model="recordModal">
      <Gallery :imgList="imgList"></Gallery>
    </Modal>
  </div>
</template>

<script>
import {
  getHistoryData,
  getAvatar,
  getTypeList,
  getDownloadUrl
} from "../../controllers/record";

import Ajax from "../../libs/ajax";
import Constant from "../../libs/constants";
import _ from "lodash";
import fakeAvatar from "../../images/default_avatar.png";
import DateUtils from "../../../node_modules/iview/src/utils/date";
import moment from "moment";

export default {
  data() {
    // 默认检索3天
    const from = moment()
      .subtract(2, "days")
      .format("YYYYMMDD");
    const to = moment().format("YYYYMMDD") + "2359";
    return {
      queryName: "",
      tableLoading: true,
      queryDateRange: [
        DateUtils.parse(from, "yyyyMMdd"),
        DateUtils.parse(to, "yyyyMMddHHmm")
      ],
      recColumn: [
        {
          title: " ",
          align: "center",
          width: 30,
          render: (h, params) => {
            let isDown = params.row.isDown;
            let iconType = !isDown ? "ios-arrow-forward" : "ios-arrow-down";
            if (params.row.list && params.row.list.length > 0) {
              return h(
                "div",
                {
                  style: { cursor: "pointer" },
                  on: {
                    click: e => {
                      console.log("clicked");
                      e.stopPropagation();
                      this.expandRow(params);
                    }
                  }
                },
                [
                  h("Icon", {
                    props: { type: iconType },
                    style: { marginRight: "5px" }
                  }),
                  h("span", "")
                ]
              );
            } else {
              return h("div", { style: { marginLeft: "25px" } }, "");
            }
          }
        },
        {
          title: "抓拍照片",
          key: "rec_capture",
          align: "center",
          render: (h, { row, column, index }) => {
            //拼装url
            let imgSrc = fakeAvatar;
            let encode = row[column.key];
            if (encode) {
              imgSrc = encode;
            }
            return (
              <div>
                <img class="user-avatar" alt="抓拍照片" src={imgSrc} />
              </div>
            );
          }
        },
        {
          title: "识别照片",
          key: "user_avatar",
          align: "center",
          render: (h, { row, column, index }) => {
            //拼装url
            let imgSrc = fakeAvatar;
            let encode = row[column.key];
            if (encode) {
              imgSrc = encode;
            }
            return (
              <div>
                <img class="user-avatar" alt="显示头像" src={imgSrc} />
              </div>
            );
          }
        },
        {
          title: "姓名",
          key: "user_name",
          align: "center"
        },
        {
          title: "用户类型",
          key: "user_type",
          align: "center"
        },
        {
          title: "摄像头ID",
          key: "ipc_id",
          align: "center"
        },
        {
          title: "摄像头名字",
          key: "ipc_name",
          align: "center"
        },
        {
          title: "抓拍时间",
          key: "rec_time_display",
          align: "center"
        },
        {
          title: "抓拍下载",
          align: "center",
          width: "100",
          render: (h, { row }) => {
            let id = row.rec_id;
            let type = "register";
            let userId = row.user_id;
            //                            return (<div><img class="user-avatar" alt="显示头像" src={imgSrc}/></div>);
            //                            return (<a href='/api/record/download_capture?rec_id=${id}&type=${type}' >抓拍下载</a>);
            return h(
              "a",
              {
                attrs: {
                  //                                    href:`/api/record/download_capture?rec_id=${id}&type=${type}`,
                },
                on: {
                  click: () => {
                    getDownloadUrl(id, type).then(json => {
                      window.json = json;
                      if (json.code == 0) {
                        let path = json.data.path;
                        let name = json.data.name;
                        let dir = json.data.dir;
                        this.downloadByIframe(dir, path, name);
                      }
                    });
                  }
                }
              },
              "抓拍下载"
            );
          }
        }
      ],
      currentPage: 1,
      pageSize: Constant.PAGE_SIZE,
      queryWord: "",
      totalVisitHistory: 0,
      recHistory: {
        data: { total: 0, result: {} }, // 一次检索的所有数据
        total: 0,
        page: {}
      },
      typeList: [],
      queryUserType: "",
      imgList: [],
      recordModal: false
    };
  },
  created() {
    this.getRec();
    this.initTypeList();
  },
  computed: {
    recDataList: function() {
      return _.map(this.recHistory.page, v => v);
    },
    currentIndex: function() {
      return (this.currentPage - 1) * this.pageSize;
    }
  },
  methods: {
    rowClassName(row, index) {
      let cls = "";
      // if (row.isExpand) {
      //   cls = "table-info-shrink ";
      // }
      if (row.liveness == "0") {
        cls += "table-info-not-live";
      } else if (row.liveness == "1") {
        cls += "table-info-live";
      } else if (row.liveness == "-2") {
        cls += "table-info-error";
      }
      return cls;
    },
    getRec(page) {
      //获取分页参数，请求后端数据
      this.tableLoading = true;
      let dateFrom = "";
      let dateTo = "";
      if (
        this.queryDateRange.length > 1 &&
        this.queryDateRange[0] != null &&
        this.queryDateRange[1] != null
      ) {
        dateFrom = DateUtils.format(this.queryDateRange[0], "yyyyMMddHHmmss");
        dateTo = DateUtils.format(this.queryDateRange[1], "yyyyMMddHHmmss");
      }
      getHistoryData(
        this.currentPage,
        this.pageSize,
        "register",
        this.queryName,
        this.queryUserType,
        dateFrom,
        dateTo
      ).then(json => {
        this.tableLoading = false;
        //检测状态码
        if (json.code !== 0) {
          //非正常就返回空表
          return;
        }
        let data = json.data;
        //检测数据块存在及长度
        if (data === undefined) {
          return;
        }
        this.recHistory.data = this.formatHistoryData(data);
        this.pageQuery(this.currentPage);
      });
    },
    expandRow(params) {
      //判断当前行是否展开，如果未展开，执行以下方法，先展开再请求接口加载到tabledata中当前data index 后
      //this.recHistory.page
      console.log(params);

      if (!params.row.isDown) {
        this.recHistory.page[params.index].isDown = true;
        let newArrayData = params.row.list;
        newArrayData.map(item => {
          item.isExpand = true;
          item.upLevelIndex = params.index;
        });
        newArrayData.map((value, key) => {
          this.recHistory.page.splice(params.index + key + 1, 0, value);
        });
        // });
      } else {
        //如果当前行已展开，则隐藏
        this.recHistory.page[params.index].isDown = false;
        this.recHistory.page.splice(params.index + 1, params.row.list.length);
      }
    },
    formatHistoryData(data) {
      let result = [];
      let tmp = undefined;
      for (let i = 0; i < data.result.length; i++) {
        data.result[i].rec_time_display = DateUtils.format(
          DateUtils.parse(data.result[i].rec_time, "yyyyMMddHHmmss"),
          "yyyy-MM-dd HH:mm:ss"
        );

        if (tmp == undefined) {
          tmp = data.result[i];
        } else {
          if (tmp.list == undefined) {
            tmp.list = [];
          }
          tmp.list.push(data.result[i]);
        }

        let j = i + 1;
        if (
          (i == data.result.length - 1 ||
            data.result[i].user_id != data.result[j].user_id) &&
          tmp != undefined
        ) {
          result.push(tmp);
          tmp = undefined;
        }
      }

      return {
        result: result
      };
    },
    pageQuery(page) {
      this.currentPage = page;
      const totalCnt = this.recHistory.data.result.length;
      let pageData = [];
      if (this.recHistory.data.result.length > 0) {
        const start = (this.currentPage - 1) * this.pageSize;
        const end = start + this.pageSize;
        pageData = this.recHistory.data.result.slice(start, end);
      }

      let { total, data } = transHistoryData({
        total: totalCnt,
        result: pageData
      });
      this.recHistory.total = total;
      this.recHistory.page = data;
    },
    downloadByIframe(dir, path, name) {
      let url =
        Ajax.BASE_URL +
        `/api/record/download_capture?path=${path}&dir=${dir}&name=${name}`;
      var iframe = document.getElementById("myIframe");
      if (iframe) {
        iframe.src = url;
      } else {
        iframe = document.createElement("iframe");
        iframe.style.display = "none";
        iframe.src = url;
        iframe.id = "myIframe";
        document.body.appendChild(iframe);
      }
    },
    // asyncAvatar(keys) {
    //     _.forEach(keys,key=>{
    //         getAvatar(key.rec_id,key.user_id).then(json => {
    //             let result = transAvatar(json);
    //             this.recHistory.data[key.rec_id].rec_pic = result.user_capture;
    //                        this.recHistory.data[key.rec_id].user_avatar = result.user_avatar;
    //                     });
    //                 });
    //             },
    initTypeList() {
      getTypeList("1").then(json => {
        this.typeList = json.data;
      });
    },
    searchRecord() {
      if (
        this.queryDateRange.length == 0 ||
        this.queryDateRange[0] == null ||
        this.queryDateRange[1] == null
      ) {
        this.$Message.warning("请选择时间段");
        return;
      }
      this.currentPage = 1;
      this.getRec();
    },
    showRecordModal(data) {
      this.imgList = data;
      this.recordModal = true;
    }
  }
};

function transHistoryData(data) {
  // //检测状态码
  // if (json.code !== 0) {
  //     //非正常就返回空表
  //     return {total: 0, result: {}};
  // }
  // let data = json.data;
  // //检测数据块存在及长度
  // if (data === undefined) {
  //     return {total: 0, result: {}};
  // }

  let { total, result } = data;

  return {
    total: total,
    data: result
  };
}

function transAvatar(json) {
  //检测状态码
  if (json.code !== 0) {
    //非正常就返回空表
    return { user_avatar: "", user_capture: "" };
  }
  let data = json.data;
  //检测数据块存在及长度
  if (data === undefined || data.length === 0) {
    return { user_avatar: "", user_capture: "" };
  }
  //提取->检验->组装
  return data;
}
</script>
